package xyz.chaobei.feature.stream;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;

/**
 * @copyright (C), 2015-2020
 * @fileName: StreamListTest
 * @author: MRC
 * @date: 2021/2/4 22:26
 * @description:
 */
public class StreamListTest {

    public static void main(String[] args) {

        List<String> list = new ArrayList<>();
        list.add("abd");
        list.add("dcf");
        list.add("abc");
        list.add("dcf");
        list.add("aaa");
        list.add("bcd");

        Consumer<String> print = System.out::println;

        // list集合，通过map 筛选出a开头的元素
        list.stream().filter(item -> item.startsWith("a")).forEach(System.out::println);
        print.accept("----------------------------");

        // 排序 默认排序
        list.stream().sorted().filter(item -> item.startsWith("a")).forEach(System.out::println);
        print.accept("----------------------------");

        // 排序，指定排序规则
        list.stream().sorted((a, b) -> b.compareTo(a)).filter(item -> item.startsWith("a")).forEach(System.out::println);
        print.accept("----------------------------");

        List<String> numbers = new ArrayList<>();
        numbers.add("1");
        numbers.add("12");
        numbers.add("13");
        numbers.add("111");
        numbers.add("456");

        print.accept(numbers.toString());
        print.accept("----------------------------");
        // map 映射,转换为数字，顺便＋1
        numbers.stream().map(Integer::valueOf).map(item -> item + 1).forEach(System.out::println);

        print.accept("----------------------------Match");
        // match 匹配
        print.accept(numbers.toString());
        // allMatch 所有的必须匹配，才返回true
        boolean allMatch = numbers.stream().allMatch(item -> item.startsWith("1"));
        System.out.println("allMatch=" + allMatch);

        // anyMatch 其中有一个返回即可返回true
        boolean anyMatch = numbers.stream().anyMatch(item -> item.startsWith("4"));
        System.out.println("anyMatch=" + anyMatch);

        // noneMatch 没有任何一个匹配，则返回true
        boolean noneMatch = numbers.stream().noneMatch(item -> item.startsWith("d"));
        System.out.println("noneMatch=" + noneMatch);

        print.accept("----------------------------Match End");

        print.accept("----------------------------Count");
        print.accept(numbers.toString());

        long size = numbers.stream().map(Integer::valueOf).filter(num -> num % 2 == 0).count();
        System.out.println("Count 偶数=" + size);

        print.accept("----------------------------Count End");

        print.accept("----------------------------Reduce");
        // Reduce 规约
        Optional<String> optional = numbers.stream().reduce((str1, str2) -> str1 + "#" + str2);
        optional.ifPresent(System.out::println);
        print.accept("----------------------------Reduce End");
    }

}
